#!/usr/bin/env python

# coding:utf-8
'''
DMZProps
'''
import os,sys,datetime,common.db
from logging import *
from common.date_time import *

def Goods2(strCurDay):

    log(INFO,'StatDay : '+ strCurDay)
    strDay = strCurDay.replace('-','')
    
    strSql = 'delete from statisticdb.DMZPropsDay where `date`=%s'%(strDay)
    rowsDeleted = cur.execute(strSql)
    cnn.commit()
    log(INFO,'Clear current day avatar success!(DeletedCount=%d)', rowsDeleted)       

    sql = '''insert into statisticdb.DMZPropsDay(`Date`,`ZoneID`,`GoodsID`,`Count`,`Price_Money`,`Price_Coin`)
    select %s,ZoneID,GoodsID,
    sum(if(UseMeans=1,Quantity/3600,Quantity)),sum(if(PayMeans=2,Price,0)),sum(if(PayMeans=1,Price,0))
    from dmz_bill_%s.goods_detail 
    where UseMeans=2 or Quantity not in(604800,2592000,0x7fffffff)
    group by ZoneID,GoodsID'''%(strDay,strDay)

    try:
        count = cur.execute(sql)
    except Exception,data:
        log(ERROR,data)
        sys.exit(0)
        
    if count > 0:
        log(INFO,'Data inserted successful!')
    else:
        log(INFO,'No data inserted')
    
    cnn.commit()



if __name__ != "__main__":

    cnn = common.db.connect('billDB')
    cur = cnn.cursor()

    if len(sys.argv) > 3:
        strBeginDay = sys.argv[2]
        strEndDay = sys.argv[3]
        if len(strBeginDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        if len(strEndDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        for strCurDay in intervalDay(strBeginDay,strEndDay):
            Goods2(strCurDay)
    elif len(sys.argv) > 2:
        strCurDay = sys.argv[2]
        if len(strCurDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        Goods2(strCurDay)
    else:
        strCurDay = GetDay(-1) ##"2010-01-14"
        Goods2(strCurDay)

    cur.close()
    cnn.close()
